

import { IPSDEFormItem } from "@ibiz/dynamic-model-api";
import { AppServiceBase, ModelTool } from "ibiz-core";

/**
 *  表单项历史查询插件类
 *
 * @export
 * @class FormItemHistory
 * @extends {Vue}
 */
export class FormItemHistory {


    /**
     * @description 表单内配置了该插件的formItem集合
     * @type {Map<string, any>}
     * @memberof FormItemHistory
     */
    public formItemMap: Map<string, any> = new Map();

    /**
     * @description 表单集合
     * @type {Map<string, any>}
     * @memberof FormItemHistory
     */
    public formMap: Map<string, any> = new Map();

    /**
     * @description 请求回来的数据
     * @type {*}
     * @memberof FormItemHistory
     */
    public data: any;

    /**
     * @description 保存表单内配置了该插件的formItem
     * @memberof FormItemHistory
     */
    public saveFormItems(modelJson: IPSDEFormItem, actionContext: any) {
        if (!this.data) {
            this.formItemMap.set(modelJson.name, { modelJson, isLoad: false });
        } else {
            this.handleData(modelJson, actionContext);
            this.formItemMap.set(modelJson.name, { modelJson, isLoad: true });
        }
    }

    /**
     * @description 加载数据
     * @memberof FormItemHistory
     */
    public loadData(modelJson: IPSDEFormItem, actionContext: any) {
        const that: any = actionContext;
        const editor = modelJson.getPSEditor();
        // 有值的时候不获取
        if (!editor?.name || that.data[editor.name]) {
            return;
        }
        const Environment = AppServiceBase.getInstance().getAppEnvironment();
        const navParams = ModelTool.getNavigateParams(editor);
        // 判断是否有步骤标识没有就不请求
        that.$http
            .get(
                `/wfcore/${
                    that.context.srfsystemid
                }-app-${Environment.AppName.toLowerCase()}/${that.deName.toLowerCase()}/${
                    that.context[that.appDeCodeName.toLowerCase()]
                }/process-instances/alls/history`,
            )
            .then((response: any) => {
                this.data = response.data;
                for (const item of this.formItemMap.values()) {
                    if (item.isLoad == false) {
                        this.handleData(item.modelJson, actionContext);
                    }
                }
            });
    }

    /**
     * @description 处理数据
     * @memberof FormItemHistory
     */
    public handleData(modelJson: IPSDEFormItem, actionContext: any) {
        const that: any = actionContext;
        const editor: any = modelJson.getPSEditor();
        if (editor.editorParams) {
            // 如果配了field就从配置取，如果不配，就取userTaskName
            let stepid = editor.editorParams['SRFNAVPARAM.stepfield'] || 'userTaskName';
            let steps = editor.editorParams['SRFNAVPARAM.step'].split(',');
            let action = editor.editorParams['SRFNAVPARAM.action'] || '';
            // 判断数据是否有usertasks没有就不做处理
            if (this.data.usertasks && Object.values(this.data.usertasks).length > 0) {
                let message = '';
                let comments: any[] = [];
                for (let task of Object.values(this.data.usertasks) as any[]) {
                    if (steps.indexOf(task[stepid]) != -1) {
                        if (task.comments.length > 0) {
                            if (action) {
                              comments.push(...task.comments.filter((comment: any)=>{
                                return comment.type != '撤回' && comment.type == action;
                              }));                     
                            } else {
                              comments.push(...task.comments.filter((comment: any)=>{
                                return comment.type != '撤回';
                              }));
                            }
                        }
                    }
                }
                // 没有comment则不处理
                if (comments.length == 0) {
                    return;
                }
                // 排序
                comments.sort((a: any, b: any) => {
                    return new Date(a.time).getTime() - new Date(b.time).getTime();
                });
                // 组织显示内容
                for (let item of comments) {
                    if (item.fullMessage) {
                      message += `${item.fullMessage}\n                                                                            ${item.authorName}    ${item.time}\n`;
                    }
                }
                this.setFormValue({ name: editor.name, value: message },that);
            }
        }	
    }

    /**
     * @description 传数据给表单，得在表单load数据后，不然会覆盖掉
     * @memberof FormItemHistory
     */    
    public setFormValue(value: any, actionContext: any){
      const that: any = actionContext;
      if ( that.oldData && that.oldData.srfkey) {
          that.onFormItemValueChange(value);
      } else {
          setTimeout(() => {
            this.setFormValue(value,that);       
          }, 500);
      }
    }

    /**
     * 获取每个表单独有的 FormItemHistory 对象
     *
     * @static
     * @returns {FormItemHistory}
     * @memberof FormItemHistory
     */
    public getInstance(modelJson:IPSDEFormItem, actionContext:any): FormItemHistory {
        if (!this.formMap.get(actionContext.controlId)) {
          this.formMap.set(actionContext.controlId,new FormItemHistory())
        }
        return this.formMap.get(actionContext.controlId);
    }

    /**
     * @description 绘制表单项
     * @param {IPSDEFormItem} modelJson
     * @param {*} actionContext
     * @return {*} 
     * @memberof FormItemHistory
     */
    public render(modelJson:IPSDEFormItem, actionContext:any){
        // 存item 去重  没存去请求
        if (!this.data && this.formItemMap.size == 0) {
            this.loadData(modelJson, actionContext);
        }
        if (!this.formItemMap.has(modelJson.name)) {
            this.saveFormItems(modelJson, actionContext);
        }      
        return actionContext.renderFormItem(modelJson as IPSDEFormItem, undefined);
    }

    /**
     * 绘制插件
     *
     * @param h createElement对象
     * @param modelJson 表单项实例
     * @param actionContext 表单vue对象
     * @param event 事件源
     */
    public renderCtrlItem(h: any, modelJson: IPSDEFormItem, actionContext: any, event: any) {
        return this.getInstance(modelJson, actionContext).render(modelJson, actionContext);
    }


}

